// distribution/pointtocash/pointtocash.js
const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();

// 引入tDesign消息提示组件
import Message from 'tdesign-miniprogram/message/index';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,

        styledata: {
            "bg_color": "white",
            "color": "#000",
            "leftflag": true,
            // "homeflag": true,
            "name": "积分换零"
        },

        // 可兑换积分
        availablePoint: 0,

        // 兑换积分
        tPoint: "",

        // 换取零钱
        tCash: "0.00",

        isForbid: false,
        // 提现中标识
        withdrawing: false,
        textfont: "发送验证码"

    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        await this.initData()
        // this.queryBalance()
    },

    async initData(options) {
        await App.getMyFullInfo()
        this.setData({
            // isVip: true,
            isVip: App.globalData.isVip,
            uid: App.globalData.uid
            // uid: 7486
            // uid: 7455
        })

        this.getUserPoint()
    },

    // 获取&展示用户积分
    getUserPoint() {
        let params = {
            uid: this.data.uid
        }
        request.post(api.myinfo, params).then(res => {
            this.setData({
                availablePoint: res.point ? res.point : 0,
                userInfo: res ? res : {}
            })
        })
    },

    // 生成积分换零订单
    async AddTransferOrder() {
        let uid = this.data.uid
        let tPoint = this.data.tPoint

        if (!uid || !tPoint) {
            return this.showErrorMessage("兑换积分不能为空")
        }

        let params = {
            uid,
            point: tPoint
        }

        // console.log(params);
        let orderRes = await request.postall(api.pointexchange, params)
        console.log(orderRes);
        if (orderRes.code == 0) {
            // 保存兑换订单Id
            this.exId = orderRes.data
            let transferFlag = await this.applyPointTransfer(orderRes.data)
            return transferFlag
        } else {
            this.showErrorMessage(orderRes.msg)
            return false
        }
    },

    // 利用订单ID 发起积分换零平台转账
    async applyPointTransfer(Id) {
        let pointTransfer = await request.postall(api.applicationtransfer, { id: Id })
        console.log(pointTransfer);
        if (pointTransfer.code == 0) {
            // 验证码发送成功 限制发送间隔
            // this.changetip()
            this.showSuccessMessage(pointTransfer.msg)
            return true
        } else {
            // 存入失败信息，用于判断
            this.ErrorMessage = pointTransfer.msg
            this.showErrorMessage(pointTransfer.msg)
            return false
        }
    },

    // 确认兑换 生成订单、申请平台转账
    async confirmTransfer() {
        let tpoint = this.data.tPoint
        if (!tpoint) {
            this.showErrorMessage("请输入要兑换的积分数")
            return
        }

        this.setData({
            withdrawing: true
        })
        let flag = await this.AddTransferOrder()
        this.setData({
            withdrawing: false
        })
        console.log("flag", flag);
        if (flag) {
            // 重新请求 更新用户本地信息（积分）
            App.getMyFullInfo()

            // 提示完返回上一页面
            let timer = setTimeout(() => {
                clearTimeout(timer)
                wx.navigateBack({
                    delta: 1
                });
            }, 2500);
            return true
        } else {
            // this.ErrorMessage = "会员编号7545未完成实名，余额功能未开立"
            let reg = /未完成实名，余额功能未开立/
            let ErrorMessage = this.ErrorMessage
            console.log("ErrorMessage", ErrorMessage);
            console.log("reg.test(ErrorMessage)", reg.test(ErrorMessage));
            if (reg.test(ErrorMessage)) {
                let timer = setTimeout(() => {
                    clearTimeout(timer)
                    wx.showModal({
                        title: "实名提示",
                        content: "是否前往认证中心实名？",
                        showCancel: true,
                        // confirmText: text,
                        success(res) {
                            if (res.confirm) {
                                wx.navigateTo({
                                    url: '/distribution/choice/choice?current=1',
                                    success: (result) => {

                                    },
                                    fail: () => { },
                                    complete: () => { }
                                });

                            } else if (res.cancel) {
                                showToast('已取消')
                            }
                        }
                    })
                }, 3500);
            }
            return false
        }
    },

    // 倒数提示
    changetip(num = 60) {
        this.setData({
            isForbid: true
        })
        let timer = setInterval(() => {
            if (num == 1) {
                this.setData({
                    isForbid: false,
                    textfont: `发送验证码`
                })
                clearInterval(timer)
                return
            }

            num--
            this.setData({
                textfont: `重新发送${num}`
            })
        }, 1000);
    },


    // 查询会员提现余额
    async queryBalance() {
        let Balance = await request.post(api.checkAllinBalance, { uid: this.data.uid })
        let allAmount = (Balance.allAmount / 100).toFixed(2)
        // console.log("余额", Balance, allAmount);
        this.setData({
            availableMoney: allAmount
        })
    },

    // 获取对应的输入框的输入值
    inputBlur(e) {
        let valname = e.currentTarget.dataset.valname
        this.setData({
            [`${valname}`]: e.detail.value
        })

        if (valname == "tPoint") {
            this.setData({
                tCash: (e.detail.value / 100).toFixed(2)
            })
        }
    },

    // 错误提示
    showErrorMessage(content) {
        Message.error({
            context: this,
            offset: [144, 130],
            duration: 3500,
            content: content,
        });
    },
    // 成功提示
    showSuccessMessage(content) {
        Message.success({
            context: this,
            offset: [144, 130],
            duration: 2500,
            content: content,
        });
    },

    // 兑换全部输入框点击事件
    handleclick() {
        this.setData({
            tPoint: this.data.availablePoint,
            tCash: (this.data.availablePoint / 100).toFixed(2)
        })
    },

    // 跳转兑换记录页面
    gotoRecord() {
        wx.navigateTo({
            url: '/distribution/pointtocash/record',
            success: (result) => {

            },
            fail: () => { },
            complete: () => { }
        });

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})